package org.arch_learn.servlet_container.components.connector.adapters;

import org.arch_learn.servlet_container.components.Mapper;
import org.arch_learn.servlet_container.components.Service;
import org.arch_learn.servlet_container.pojo.CustomHttpServletResponse;
import org.arch_learn.servlet_container.pojo.Response;
import org.arch_learn.servlet_container.utils.HttpProtocolUtil;
import org.arch_learn.servlet_container.utils.StaticResourceUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ServletResponseAdapter {
    public static Response adaptHttpServletResponse(CustomHttpServletResponse httpServletResponse) {
        String responseText = HttpProtocolUtil.getHttp200ResponseHeader(httpServletResponse.getMessageText().getBytes().length) + httpServletResponse.getMessageText();
        return new Response(responseText);
    }

    public static Response adaptStaticResourcesServletResponse(Service service, HttpServletRequest httpServletRequest) throws FileNotFoundException {
        String absolutePath = null;
        if (httpServletRequest.getContextPath().equals("/")) {
            absolutePath = StaticResourceUtil.getAbsolutePath(httpServletRequest.getRequestURI());
        } else {
            absolutePath = Mapper.getMappedStaticResources(service, httpServletRequest);
        }

        File file = new File(absolutePath);
        if (file.exists() && file.isFile()) {
            return new Response(new FileInputStream(file));
        } else {
            String http404Response = HttpProtocolUtil.getHttp404Response();
            return new Response(http404Response);
        }
    }
}
